var express = require('express');
var db = require('../db/commonDB')
var router = express.Router();
var jwt = require('jsonwebtoken')
var userDAL = require('../DAL/userDAL')
var app = require('../app')
const bcrypt = require('bcryptjs');
var changeDAL = require('../DAL/changeDAL');
const passport = require('passport');
const AlipaySDK = require('alipay-sdk').default
const AlipayFormData = require('alipay-sdk/lib/form').default
var https = require('https');
const { json } = require('express');
const { parse } = require('path');

router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

// 注册
router.post('/register', function (req, res, next) {
    var user = req.body
    bcrypt.hash(user.user_pwd, 10, function (err, hash) {
        if (err) {
            console.log('加密错误' + err.message)
        } else {
            user.user_pwd = hash
            userDAL.addUser(user, function (err, results) {
                if (err) {
                    res.json({ code: 500, msg: '注册失败'})
                } else {
                    res.json({ code: 200, msg: '注册成功', results: results })
                }
            })
        }
    })
});

//登录
router.post('/login', function (req, res, next) {
    var user = req.body
    userDAL.searchUser(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: 'login error' })
        } else {
            userDAL.checkName(user, function (err, results) {
                if (err) {
                    res.json({
                        code: 200,
                        msg: '登录失败'
                    })
                } else {
                    var temp = { data: results }
                    var newTemp = temp.data[0].user_pwd
                    bcrypt.compare(user.user_pwd, `${newTemp}`, function (err, result) {
                        if (result) {
                            jwt.sign({ "id": user.user_id,"name":user.user_name,"pwd": user.user_pwd }, 'secret', { expiresIn: 60 * 60 * 24 }, function (err, token) {
                                if (err) {
                                    res.json({ code: 500, msg: 'token err' })
                                } else {
                                    // var a = jwt.verify(token,'secret')
                                    res.json({ code: 200, msg: 'ok', data: 'Bearer ' + token, id: temp.data[0].user_id })
                                }
                            })
                        } else {
                            res.send('密码错误，登录失败！')
                        }
                    })
                }
            })
        }
    })


});

//修改个人信息
router.post('/changeInfo', function (req, res, next) {
    var user = req.body
    userDAL.changeInfo(user, function (err) {
        if (err) {
            res.json({
                code: 200,
                msg: '修改个人信息失败'
            })
        } else {
            res.json({
                code: 200,
                msg: '修改个人信息成功'
            })
        }
    })
})
//修改密码
router.post(
    "/changepwd",
    passport.authenticate("jwt", { session: false }),
    function (req, res, next) {
        var userNewInfo = req.body;
        var userInfo = req.user; //验证调用本接口的密码是否正确
        if (userInfo.pwd == userNewInfo.oldPwd) {
            bcrypt.hash(userNewInfo.newPwd, 10, function (err, hash) {
                if (err) {
                    console.log("加密错误");
                } else {
                    userNewInfo.newPwd = hash;
                    userDAL.changePwd(userNewInfo, function (err) {
                        if (err) {
                            res.json({ code: 500, msg: "updata error" });
                        } else {
                            res.json({ code: 200, msg: "updata ok" });
                        }
                    });
                }
            });
        } else {
            res.json({ code: 501, msg: "updata error", data: "原始密码错误" });
        }
    }
);

//获取个人信息
router.get('/getUserInfo', function (req, res, next) {
    var user = req.query
    userDAL.getUserInfo(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '获取失败' })
        } else if (results.length == 0) {
            res.json({ code: 400, msg: '获取失败,查无此人' })
        } else {
            res.json({ code: 200, msg: '获取成功', results: results })
        }
    })
})

//浏览记录
router.get('/browseRecords', function (req, res, next) {
    var user = req.query
    userDAL.selectFootPrint(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '查看失败', error: err })
        } else {
            res.json({ code: 200, msg: '查看成功', results: results })
        }
    })
});

//删除浏览记录
router.post('/delBrowseRecords', function (req, res, next) {
    var user = req.body
    userDAL.delFootPrint(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '删除失败', error: err.message })
        } else {
            res.json({ code: 200, msg: '删除成功', results: results })
        }
    })
});

router.post('/getAllProuductById',function(req,res,next){
    var user = req.body
    userDAL.getAllProuductById(user,function(err,results){
        if (err) {
            res.json({ code: 500, msg: '获取失败', error: err.message })
        } else {
            res.json({ code: 200, msg: '获取成功', results: results.length })
        }
    })
})
//获取手机验证码
router.get('/getValidCode', function (req, res, next) {
    //1.接受手机号参数
    //生成随机数验证码
    var randomNum = Math.floor(Math.random() * (9999 - 1000)) + 1000;
    var mobile = req.query.user_phone
    //2.拼接第三方接口url
    var account = 'c82272037'
    var password = '9036fbc5d65f372280ad87dfceab6558'
    var content = '您的验证码是：' + randomNum + '。请不要把验证码泄露给其他人。'
    var url = `https://106.ihuyi.com/webservice/sms.php?method=Submit&account=${account}&password=${password}&mobile=${mobile}&content=${content}`
    //3.http模块调用第三方模块
    https.get(url, function (response) {
        var result = ''
        response.on('data', function (chunk) {
            result += chunk
        })
        response.on('end', function () {
            var code = /<code>(\d+)<\/code>/.exec(result)[1]
            res.json({ code: 200, msg: 'ok', data: code, Num: randomNum })
        })
    })
});
//查看收藏记录
router.get('/viewCollection', function (req, res, next) {
    var user = req.query
    userDAL.viewCollection(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '查看失败', error: err })
        } else {
            res.json({ code: 200, msg: '查看成功', results: results })
        }
    })
});
//删除收藏记录
router.post('/delViewCollection', function (req, res, next) {
    var favorites = req.body
    userDAL.delViewCollection(favorites, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '删除失败', error: err })
        } else {
            res.json({ code: 200, msg: '删除成功', results: results })
        }
    })
});
//添加收藏商品
router.post('/addCollection', function (req, res, next) {
    var user = req.body
    userDAL.addCollection(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '添加失败', error: err })
        } else {
            res.json({ code: 200, msg: '添加成功', results: results })
        }
    })
});
//删除已收藏的商品
router.post('/delCollection', function (req, res, next) {
    var user = req.body
    userDAL.delCollection(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '删除失败', error: err })
        } else {
            res.json({ code: 200, msg: '删除成功', results: results })
        }
    })
});

//根据用户id和商品id删除购物车商品
router.post('/delCartProduct', function (req, res, next) {
    var user = req.body
    userDAL.delCartProduct(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '删除失败', error: err })
        } else {
            res.json({ code: 200, msg: '删除成功', results: results })
        }
    })
});
//显示用户收藏
router.get('/getAllCollection', function (req, res, next) {
    var user = req.query
    userDAL.getAllCollection(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '显示失败', error: err })
        } else {
            res.json({ code: 200, msg: '显示成功', results: results })
        }
    })
});
//显示社区部分内容
router.get('/getCommunityInfo',function(req,res,next){
    userDAL.getCommunityInfo('', function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '显示失败', error: err })
        } else {
            res.json({ code: 200, msg: '显示成功', results: results })
        }
    })
}),
//显示社区内容
router.get('/getCommunity', function (req, res, next) {
    // var user = req.query
    userDAL.getCommunity('', function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '显示失败', error: err })
        } else {
            res.json({ code: 200, msg: '显示成功', results: results })
        }
    })
});
//根据文章id查询对应文章内容
router.get('/getEssayByThemeId', function (req, res, next) {
    var user = req.query
    userDAL.getEssayByThemeId(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '显示失败', error: err })
        } else {
            res.json({ code: 200, msg: '显示成功', results: results })
        }
    })
});
//社区点赞
router.get('/getColor', function (req, res, next) {
    var user = req.query
    userDAL.getColor(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '显示失败', error: err })
        } else {
            res.json({ code: 200, msg: '显示成功', results: results })
        }
    })
});
router.post('/addcolor', function (req, res, next) {
    var user = req.body
    userDAL.addcolor(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '添加失败', error: err })
        } else {
            res.json({ code: 200, msg: '添加成功', results: results })
        }
    })
});

router.post('/delcolor', function (req, res, next) {
    var user = req.body
    userDAL.delcolor(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '删除失败', error: err })
        } else {
            res.json({ code: 200, msg: '删除成功', results: results })
        }
    })
});
router.get('/viewcolor', function (req, res, next) {
    var user = req.query
    userDAL.viewcolor(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '查看失败', error: err })
        } else {
            res.json({ code: 200, msg: '查看成功', results: results })
        }
    })
});

//添加商品评价
router.post('/addconm', function (req, res, next) {
    
    var p_comm = req.body
    userDAL.addconm(p_comm, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '添加失败', error: err })
        } else {
            res.json({ code: 200, msg: '添加成功', results: results })
        }
    })
});
//查看评价
router.get('/viewconm', function (req, res, next) {
    var user = req.query
    userDAL.viewconm(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '查看失败', error: err })
        } else {
            res.json({ code: 200, msg: '查看成功', results: results })
        }
    })
});
//根据用户id查看点赞表
router.get('/viewuserconm', function (req, res, next) {
    var user = req.query
    userDAL.viewuserconm(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '查看失败', error: err })
        } else {
            res.json({ code: 200, msg: '查看成功', results: results })
        }
    })
});
router.get('/getcomnColor', function (req, res, next) {
    var user = req.query
    userDAL.getcomnColor(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '显示失败', error: err })
        } else {
            res.json({ code: 200, msg: '显示成功', results: results })
        }
    })
});

//评论点赞功能
router.post('/comaddcolor', function (req, res, next) {
    var user = req.body
    userDAL.comaddcolor(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '添加失败', error: err })
        } else {
            res.json({ code: 200, msg: '添加成功', results: results })
        }
    })
});
//取消评论点赞功能
router.post('/delcomcolor', function (req, res, next) {
    var user = req.body
    userDAL.delcomcolor(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '添加失败', error: err })
        } else {
            res.json({ code: 200, msg: '添加成功', results: results })
        }
    })
})


router.post('/getFavState', function (req, res, next) {
    var user = req.body
    userDAL.getFavState(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '查看失败', error: err })
        } else {
            res.json({ code: 200, msg: '查看成功', results: results })

        }
    })
});
//发布社区文章
router.post('/releaseArticle', function (req, res, next) {
    var user = req.body
    userDAL.releaseArticle(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '发布失败', error: err })
        } else {
            res.json({ code: 200, msg: '发布成功', results: results })

        }
    })
});
//发布文章上传图片
router.post('/uploadImg', function (req, res, next) {
    var user = req.body
    userDAL.uploadImg(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '发布失败', error: err })
        } else {
            res.json({
                // errno 即错误代码，0 表示没有错误。
                //       如果有错误，errno != 0，可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
                "errno": 0,
            
                // data 是一个数组，返回图片Object，Object中包含需要包含url、alt和href三个属性,它们分别代表图片地址、图片文字说明和跳转链接,alt和href属性是可选的，可以不设置或设置为空字符串,需要注意的是url是一定要填的。
                "data": [
                    {
                        url: "图片地址",
                        alt: "图片文字说明",
                        href: "跳转链接"
                    },
                    {
                        url: "图片地址1",
                        alt: "图片文字说明1",
                        href: "跳转链接1"
                    },
                    "……"
                ]
            })

        }
    })
});
//生成支付页面
router.get(
    "/pay",
    passport.authenticate("jwt", {
        session: false
    }),
    async function (req, res, next) {
        let price = 0
        let orders = req.query;
        let a = [orders.orders].forEach((item) => {
            let b = JSON.parse(item)
            let c = Object.values(b)
            c.forEach((result)=>{
                price += result.orders_goods_price*result.orders_goods_count
            })
        })
        let orders_id = Object.values(JSON.parse([orders.orders]))[0].orders_id
        const alipaySdk = new AlipaySDK({
            appId: "2021000118637395", // 开放平台上创建应用时生成的 appId
            signType: "RSA2", // 签名算法,默认 RSA2
            gateway: "https://openapi.alipaydev.com/gateway.do", // 支付宝网关地址 ，沙箱环境下使用时需要修改
            privateKey: "MIIEoAIBAAKCAQEApv5FC1pWxPTvOGXcuQeC5Jp4a7QJaYuKWLBAhpnRs8fc3Dm2+OrxibytLeVZbUxD8PX5Fn74z64eTu/wKo34dy6SHUhjwYOS1geuLTcfTmMETVZJ1MYJpZDcVam2MgZjb0/JV7+iXBjS9bInZvVEzVndWgLG/AEyvf7FLzNC5QAt4ZlkICWLv0ZmU+xdDG37HLT6sTV9CKmvxnix6gdN+B0AhWBNQ1FmpyRfXU9+1XqDO+OpDLEA3SQr7bdwiOIg3zZQ3SlI1dPNfKzSGs3Chby8Fnou91LDIS8sQ9DGETLLhImjiJFVPDohVl7OabCmz+tVpE0yBnKWD9IoKyjJxwIDAQABAoH/fT42ik02xoDs6V98K0l24fz4U86zQ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cQdIQJCK+B8wWjco7HV3QvXjv5Zo8bELSa5ZsFSnIpwQPyIV+5fzV/W/NAl2DBMAxSG3EQYBbTTwrqTumdopBSOVlNCpj9ht0A5DCrsMoHD", //支付宝私钥
            alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1pD5m7pzACNpQ5ugJQO2LlPhflCYQ9GkAOKD8ycJtRe3ys4gnbftgkQtytfseiCv7I+h9z4nOR+MsK+HT8Zg+oqP0k84PeAUmlHt2VMxrS+vB8lfwP/hA0Ca9UTyAr0sXtc0b1lEPYcYN8LHjvXhXWyIcSDi4G0dXiNXXjGQnr6kygwBRzanVhvc7NsIswQOeHIQNbkMXHN/9L/3qBRtdVwqKUQovlq5xQuDiVZheEwyEOdtqB+vIhV50ID4DlQ1QlpJPAHmm5xi/lod1n+84hpr+2BwtUOqAefY+UujBzRCUDqQe4HNpUHqs7NPH9asrCwrZ6uubQlWBm9xKTYLYwIDAQAB", // 支付宝公钥，需要对结果验签时候必填
        });
        const formData = new AlipayFormData();
        formData.setMethod("get");
        formData.addField("notifyUrl", "http://localhost:3000/callback");
        formData.addField("bizContent", {
            outTradeNo: orders_id,
            productCode: "FAST_INSTANT_TRADE_PAY",
            totalAmount: parseFloat(price),
            subject: "YIJI",
            body: "1",
        });
        formData.addField(
            "returnUrl",
            `http://localhost:8080/paysuccess?orderid=${orders_id}`
        );
        const result = await alipaySdk.exec(
            "alipay.trade.page.pay", {}, {
            formData: formData
        }
        );
        res.json({
            code: 200,
            msg: "pay hahahaah!",
            data: result
        });
    }
);
//通过文章的用户id获取用户信息
router.post('/getUserInfoBytheme', function (req, res, next) {
    var user = req.body
    userDAL.getUserInfoBytheme(user, function (err, results) {
        if (err) {
            res.json({ code: 500, msg: '获取失败', error: err })
        } else {
            res.json({ code: 200, msg: '获取成功', results: results })

        }
    })
});
module.exports = router;